/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.appspot.trafficando.infrastructure.provider;

import com.appspot.trafficando.domain.EventCategory;
import com.appspot.trafficando.domain.EventType;
import com.google.appengine.repackaged.com.google.common.base.CharMatcher;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.abdera.model.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Domenico Maria Giffone
 */
public class CCISSEventProvider extends RSSEventProvider {

    private static final Logger LOG = LoggerFactory.getLogger(CCISSEventProvider.class);
    private static CharMatcher markupSantizer = CharMatcher.is('\n').or(CharMatcher.WHITESPACE);
    // Keyword, Term
    private Map<String, String> datexEventKeywords;

    public void setDatexEventKeywords(Map<String, String> datexEventKeywords) {
        this.datexEventKeywords = datexEventKeywords;
    }

    @Override
    protected List<EventCategory> getCategories(Entry entry) {
        List<EventCategory> result = new ArrayList<EventCategory>();
        //StringBuilder sb = new StringBuilder();
        for (String keyword : datexEventKeywords.keySet()) {
            //sb.append(debugBytes(entry.getSummary(), keyword));
            if (startsWithIgnoreCase(entry.getSummary(), keyword)) {
                result.add(EventType.TRAFFIC.categoryForTerm(datexEventKeywords.get(keyword)));
                break;
            }
        }
        if (result.isEmpty()) {
            LOG.error("Cannot match event category for entry '{}' === '{}'", entry.getTitle(), entry.getSummary());
            //LOG.error(sb.toString());
        }

        //not possible ?!?
//        if (result.size() > 1) {
//            LOG.error("Too many category matches {}, for entry '{}' === '{}'", entry.getTitle(), entry.getSummary());
//        }
        return result;
    }

    private boolean startsWithIgnoreCase(String str, String prefix) {
        if (str == null || prefix == null) {
            return false;
        }
        if (str.startsWith(prefix)) {
            return true;
        }
        if (str.length() < prefix.length()) {
            return false;
        }
        String lcStr = str.substring(0, prefix.length()).toLowerCase();
        String lcPrefix = prefix.toLowerCase();
        return lcStr.equals(lcPrefix);
    }

    /*private String debugBytes(String str, String prefix) {
    StringBuilder sb = new StringBuilder();
    String lcStr = str.substring(0, prefix.length()).toLowerCase();
    String lcPrefix = prefix.toLowerCase();
    sb.append(lcPrefix + " = " + lcStr).append("\n");
    sb.append("> keyword >" + prettyPrintHex(lcPrefix.getBytes(Charsets.UTF_16)) + "<").append("\n");
    sb.append("  summary >" + prettyPrintHex(lcStr.getBytes(Charsets.UTF_8)) + "<").append("\n");
    return sb.append("\n").toString();
    }*/
    @Override
    protected void sanitizeEntry(Entry entry) {
        final String summary = markupSantizer.collapseFrom(entry.getSummary(), ' ');
        //summary.replaceAll("<br/> (Fonte:<a href=\\\"http://www.cciss.it\\\" target=\\\"_new\\\">www.cciss.it<\/a>)", "");
        entry.setSummary(summary);
    }

    /*private String prettyPrintHex(byte[] data) {
    int i = 0, j = 0;   // loop counters
    int line_addr = 0;  // memmory address printed on the left
    String line_to_print = "";
    if (data.length == 0) {
    return "";
    }
    StringBuilder _sbbuffer = new StringBuilder();
    //Loop through every input byte
    String _hexline = "";
    String _asciiline = "";
    for (i = 0, line_addr = 0; i < data.length; i++, line_addr++) {
    _hexline = _hexline.concat(String.format("%#04x ", data[i]));
    if (data[i] > 31 && data[i] < 127) {
    _asciiline = _asciiline.concat(String.valueOf((char) data[i]));
    } else {
    _asciiline = _asciiline.concat(".");
    }
    }
    // Handle the ascii for the final line, which may not be completely filled.
    if (i % 16 > 0) {
    for (j = 0; j < 16 - (i % 16); j++) {
    _hexline = _hexline.concat("     ");
    }
    _sbbuffer.append(_hexline);
    _sbbuffer.append("\t...\t");
    _sbbuffer.append(_asciiline);
    }
    return _sbbuffer.toString();
    }*/
}
